package com.wang.tool.util;

import com.wang.tool.monitor.LinkLogUtil;

import java.util.function.Function;

public class PageScanUtil {

    /**
     * scan
     *
     * @param action   biz_code log use
     * @param pageSize query size every time
     * @param maxTimes maxTry null -> not check maxTimes
     * @param scanner  search
     */
    public static void scan(String action, Integer pageSize, Integer maxTimes, Function<ScanParam, Object> scanner) {
        int times = 0;
        Object lastVal = null;
        try {
            do {
                ScanParam scanParam = ScanParam.build(lastVal, pageSize);
                lastVal = scanner.apply(scanParam);
                times += 1;
                LinkLogUtil.info("PageScanUtil_scan, action:{0}, pageSize:{1}, times:{2}, lastVal:{3}", action, pageSize, times, lastVal);
                if (lastVal != null && maxTimes != null && times >= maxTimes) {
                    LinkLogUtil.warn("PageScanUtil_scan_over_times, action:{0}, pageSize:{1}, times:{2}, lastVal:{3}", action, pageSize, times, lastVal);
                    break;
                }
            } while (lastVal != null);
        } catch (Throwable e) {
            LinkLogUtil.error("PageScanUtil_scan_error", e, "action:{0}, pageSize:{1}, times:{2}, error:{3}", action, pageSize, times);
            throw e;
        }
    }


    /**
     * scan
     *
     * @param code     biz_code log use
     * @param pageSize query size every time
     * @param maxTimes maxTry null -> not check maxTimes
     * @param scanner  search return true means continue scan
     */
    public static void page(String code, Integer pageSize, Integer maxTimes, Function<PageParam, Boolean> scanner) {
        int times = 0;
        Boolean continueScan = null;
        try {
            do {
                PageParam scanParam = PageParam.of(times, pageSize);
                continueScan = scanner.apply(scanParam);
                times += 1;
                LinkLogUtil.info("PageScanUtil_page, code:{0}, pageSize:{1}, times:{2}, continueScan:{3}", code, pageSize, times, continueScan);
                if (continueScan != null && continueScan && maxTimes != null && times >= maxTimes) {
                    LinkLogUtil.warn("PageScanUtil_page_over_times, code:{0}, pageSize:{1}, times:{2}", code, pageSize, times);
                    break;
                }
            } while (continueScan != null && continueScan);
        } catch (Throwable e) {
            LinkLogUtil.error("PageScanUtil_page_error", e, "action:{0}, pageSize:{1}, times:{2}, error:{3}", code, pageSize, times);
            throw e;
        }
    }

}
